<template>
  <div
    v-if="activatedNode.compData.inputData"
    class="data-box"
  >
    <el-collapse v-model="collapseNames">
      <el-collapse-item title="输入参数" name="param">
        <div
          v-if="activatedNode.compData.inputParamList && activatedNode.compData.inputParamList.length > 0"
          class="data-list"
        >
          <div
            class="data-item"
            v-for="(param, index) in activatedNode.compData.inputParamList || []"
            :key="index"
          >
            <div class="label" style="margin-right: 5px;">
              <el-input
                v-model="param.name"
                @change="initNodeOptions()"
                size="small"
                title="参数名"
              />
            </div>
            <div v-if="param.input" style="flex-grow: 1">
              <el-input v-model="param.value" title="默认值" size="small" />
            </div>
            <div v-else style="flex-grow: 1">
              <ac-select
                v-model="param.value"
                :options="globalParamOptions"
                title="默认值"
                size="small"
              />
            </div>
            <div style="margin-left: 5px;flex-shrink: 0">
              <ac-switch
                v-model="param.input"
                :options="[{key: true, value: ''}, {key: false, value: ''}]"
                title="手动输入"
                size="small"
              />
            </div>
            <ac-icon
              iconId="018dc9c3efd3a0502886"
              title="删除"
              color="red"
              @click="deleteInputParam(index)"
            />
          </div>
        </div>
        <div class="data-add-box">
          <div class="data-add" @click="addInputParam">
            <ac-icon iconId="018dca3b4707c4c43a2f" />
            <span style="margin-left: 5px;font-size: 13px;">添加参数</span>
          </div>
        </div>
      </el-collapse-item>
      <el-collapse-item title="数据源" name="dataSource">
        <div class="data-list">
          <div class="data-item">
            <div class="label">数据类型：</div>
            <div class="content">
              <ac-select
                v-model="activatedNode.compData.dataSourceType"
                options="静态数据,输入参数,数据模型,视图,脚本"
                size="small"
                @change="changeDataSourceType"
              />
              <ac-icon
                v-if="activatedNode.compData.dataSourceType === '静态数据'"
                iconId="018ece4f695f6947a2a8"
                @click.stop="editDataList(activatedNode.compData.dataJson)"
              />
            </div>
          </div>
          <div class="data-item" v-if="activatedNode.compData.dataSourceType === '静态数据'">
            <div class="content">
              <ac-textarea
                v-model="activatedNode.compData.dataJson"
                :rows="10"
                size="small"
                @change="changeDataJson"
              />
            </div>
          </div>
          <div class="data-item" v-if="activatedNode.compData.dataSourceType === '输入参数'">
            <div class="label">输入参数：</div>
            <div class="content">
              <ac-select
                v-model="activatedNode.compData.inputParamId"
                size="small"
                :options="inputParamOptions"
              />
            </div>
          </div>
          <div class="data-item" v-if="activatedNode.compData.dataSourceType === '数据模型'">
            <div class="label">数据模型：</div>
            <div class="content">
              <ac-tree
                v-model="activatedNode.compData.dataModelId"
                data-url="/system/dataModel/queryTree"
                typeSelect="model"
                size="small"
                @change="changeDataModel"
              />
            </div>
          </div>
          <div class="data-item" v-if="activatedNode.compData.dataSourceType === '视图'">
            <div class="label">视图：</div>
            <div class="content">
              <ac-tree
                v-model="activatedNode.compData.viewId"
                data-url="/system/view/queryTree"
                typeSelect="view"
                size="small"
                @change="changeView"
              />
            </div>
          </div>
          <div class="data-item" v-if="activatedNode.compData.dataSourceType === '脚本'">
            <div class="label">脚本：</div>
            <div class="content">
              <ac-tree
                v-model="activatedNode.compData.scriptId"
                data-url="/system/scriptGroovy/queryTree"
                type-select="script"
                size="small"
                @change="changeScript"
              />
            </div>
          </div>
        </div>
      </el-collapse-item>
      <el-collapse-item
        v-if="activatedNode.compData.dataSourceType === '输入参数'
          || activatedNode.compData.dataSourceType === '数据模型'
          || activatedNode.compData.dataSourceType === '视图'
          || activatedNode.compData.dataSourceType === '脚本'"
        :title="(activatedNode.compData.dataSourceType === '输入参数'
          || activatedNode.compData.dataSourceType === '脚本') ? '输入参数' : '数据过滤'"
        name="dataFilter"
      >
        <div
          v-if="activatedNode.compData.dataSourceType === '脚本'
            || activatedNode.compData.dataSourceType === '输入参数'"
          class="data-list"
        >
          <div
            class="data-item"
            v-for="(filter, index) in activatedNode.compData.filterList || []"
            :key="index"
          >
            <div class="label" style="margin-right: 5px;">
              <ac-input
                v-model="filter.fieldId"
                placeholder="参数名"
                size="small"
                title="参数名"
              />
            </div>
            <div v-if="filter.manually" style="flex-grow: 1">
              <el-input v-model="filter.compareValue" title="参数值" size="small" />
            </div>
            <div v-else style="flex-grow: 1">
              <ac-select
                v-model="filter.compareValue"
                :options="nodeOptions"
                title="参数值"
                size="small"
              />
            </div>
            <div style="margin-left: 5px;flex-shrink: 0">
              <ac-switch
                v-model="filter.manually"
                :options="[{key: true, value: ''}, {key: false, value: ''}]"
                title="手动输入"
                size="small"
              />
            </div>
            <ac-icon
              iconId="018dc9c3efd3a0502886"
              title="删除过滤"
              color="red"
              @click="deleteFilter(index)"
            />
          </div>
          <div class="data-add-box">
            <div class="data-add">
              <ac-icon iconId="018dca3b4707c4c43a2f" />
              <span style="font-size: 13px;" @click="addFilter">添加参数</span>
              <ac-icon style="margin-left: 15px" iconId="018ece4f72d1bf69178b" />
              <span style="font-size: 13px" @click="addAllFilter">一键添加</span>
            </div>
          </div>
        </div>
        <div class="filter" v-else>
          <div
            class="data-list"
            v-for="(filter, index) in activatedNode.compData.filterList || []"
            :key="index"
          >
            <div class="data-item">
              <span class="label">拼接方式：</span>
              <ac-select v-model="filter.connectSymbol" options="and,or" size="small" />
              <ac-icon
                v-if="index > 0 && index < (activatedNode.compData.filterList || []).length"
                iconId="018fa3973ded010d7ef2"
                title="上移"
                style="margin-left: 10px"
                @click="moveFilterUp(index)"
              />
              <ac-icon
                v-if="index < (activatedNode.compData.filterList || []).length - 1"
                iconId="018fa397630c01052d7e"
                title="下移"
                @click="moveFilterDown(index)"
              />
              <ac-icon
                iconId="018dc9c3efd3a0502886"
                title="删除过滤"
                color="red"
                @click="deleteFilter(index)"
              />
            </div>
            <div class="data-item">
              <span class="label">前置括号：</span>
              <span class="content">
                <ac-select v-model="filter.frontBracket" options="(,((,(((,((((" size="small" />
              </span>
            </div>
            <div class="data-item">
              <span class="label">过滤字段：</span>
              <span class="content">
                <ac-select v-model="filter.fieldId" :options="fieldIdList" size="small" />
              </span>
            </div>
            <div class="data-item">
              <span class="label">比较符：</span>
              <span class="content">
                <ac-select
                  v-model="filter.compareSymbol"
                  options="大于,大于等于,等于,小于,小于等于,不等于,模糊"
                  size="small"
                />
              </span>
            </div>
            <div class="data-item">
              <span class="label">比较值：</span>
              <div v-if="filter.manually" style="flex-grow: 1;">
                <el-input v-model="filter.compareValue" size="small" />
              </div>
              <div v-else style="flex-grow: 1">
                <ac-select
                  v-model="filter.compareValue"
                  :options="nodeOptions"
                  title="比较值"
                  size="small"
                />
              </div>
              <div style="margin-left: 5px;flex-shrink: 0">
                <ac-switch
                  v-model="filter.manually"
                  :options="[{key: true, value: ''}, {key: false, value: ''}]"
                  title="手动输入"
                  size="small"
                />
              </div>
            </div>
            <div class="data-item">
              <span class="label">后置括号：</span>
              <span class="content">
                <ac-select v-model="filter.behindBracket" options="),)),))),))))" size="small" />
              </span>
            </div>
          </div>
          <div class="data-add-box">
            <div class="data-add" @click="addFilter">
              <ac-icon iconId="018dca3b4707c4c43a2f" />
              <span style="margin-left: 5px;font-size: 13px;">添加过滤</span>
            </div>
          </div>
        </div>
      </el-collapse-item>
      <el-collapse-item
        v-if="activatedNode.compData.dataSourceType === '数据模型'
          || activatedNode.compData.dataSourceType === '视图'"
        title="数据排序"
        name="dataOrdinal"
      >
        <div class="filter">
          <div
            class="data-list"
            v-for="(ordinal, index) in activatedNode.compData.ordinalList || []"
            :key="index"
          >
            <div class="data-item" style="justify-content: start">
              <div style="flex-shrink: 0;margin-right: 5px;width:130px;">
                <ac-select v-model="ordinal.fieldId" :options="fieldIdList" size="small" />
              </div>
              <div style="flex-shrink: 0;width:100px;">
                <ac-select v-model="ordinal.ordinalMode" options="升序,降序" size="small" />
              </div>
              <ac-icon
                v-if="index > 0 && index < (activatedNode.compData.ordinalList || []).length"
                iconId="018fa3973ded010d7ef2"
                title="上移"
                style="margin-left: 10px"
                @click="moveOrdinalUp(index)"
              />
              <ac-icon
                v-if="index < (activatedNode.compData.ordinalList || []).length - 1"
                iconId="018fa397630c01052d7e"
                title="下移"
                style="margin-left: 10px"
                @click="moveOrdinalDown(index)"
              />
              <ac-icon
                iconId="018dc9c3efd3a0502886"
                title="删除过滤"
                color="red"
                @click="deleteOrdinal(index)"
              />
            </div>
          </div>
          <div class="data-add-box">
            <div class="data-add" @click="addOrdinal">
              <ac-icon iconId="018dca3b4707c4c43a2f" />
              <span style="margin-left: 5px;font-size: 13px;">添加排序</span>
            </div>
          </div>
        </div>
      </el-collapse-item>
      <el-collapse-item
        v-if="activatedNode.compData.dataSourceType === '数据模型'
          || activatedNode.compData.dataSourceType === '视图'"
        title="数据查询"
        name="dataQuery"
      >
        <div class="data-list">
          <div class="data-item">
            <div class="label">自动更新：</div>
            <div class="content">
              <ac-switch
                v-model="activatedNode.compData.autoload"
                :options="[{key: true, value: ''}, {key: false, value: ''}]"
                size="small"
              />
            </div>
          </div>
          <div class="data-item" v-if="activatedNode.compData.autoload">
            <div class="label">
              <el-tooltip content="单位：秒">
                <span>更新间隔<ac-icon iconId="018dca8ec9890493be26" style="margin-left: 5px"/>：</span>
              </el-tooltip>
            </div>
            <div class="content">
              <ac-number
                v-model="activatedNode.compData.autoInterval"
                size="small"
                point="0"
              />
            </div>
          </div>
          <div class="data-item">
            <div class="label">开启分页：</div>
            <div class="content">
              <ac-switch
                v-model="activatedNode.compData.dataPage"
                :options="[{key: true, value: ''}, {key: false, value: ''}]"
                size="small"
              />
            </div>
          </div>
          <div class="data-item" v-if="activatedNode.compData.dataPage">
            <div class="label">每页数量：</div>
            <div class="content">
              <ac-number
                v-model="activatedNode.compData.dataPageSize"
                size="small"
                point="0"
              />
            </div>
          </div>
          <div class="data-item" v-if="activatedNode.compData.dataPage">
            <div class="label">分页加载方式：</div>
            <div class="content">
              <ac-buttons
                v-model="activatedNode.compData.dataLoadMode"
                size="small"
                :options="[
                  {key: 'pagination', value: '分页导航'},
                  {key: 'bottom', value: '滚动到底部加载'}
                ]"
              />
            </div>
          </div>
          <div
            v-if="activatedNode.compData.dataPage
              && activatedNode.compData.dataLoadMode === 'pagination'"
            class="data-item"
          >
            <div class="label">显示跳转：</div>
            <div class="content">
              <ac-switch
                v-model="activatedNode.compData.showJumper"
                size="small"
                :options="[
                  {key: true, value: ''},
                  {key: false, value: ''}
                ]"
              />
            </div>
          </div>
          <div
            v-if="activatedNode.compData.dataPage
              && activatedNode.compData.dataLoadMode === 'pagination'"
            class="data-item"
          >
            <div class="label">每页数量选择：</div>
            <div class="content">
              <ac-switch
                v-model="activatedNode.compData.showSizes"
                size="small"
                :options="[
                  {key: true, value: ''},
                  {key: false, value: ''}
                ]"
              />
            </div>
          </div>
          <div
            v-if="activatedNode.compData.dataPage
              && activatedNode.compData.dataLoadMode === 'pagination'"
            class="data-item"
          >
            <div class="label">页码按钮数：</div>
            <div class="content">
              <ac-number
                v-model="activatedNode.compData.pagerCount"
                size="small"
                point="0"
              />
            </div>
          </div>
          <div class="data-item" v-if="!activatedNode.compData.dataPage">
            <div class="label">查询总数：</div>
            <div class="content">
              <ac-number
                v-model="activatedNode.compData.dataQueryTotal"
                size="small"
                point="0"
              />
            </div>
          </div>
        </div>
      </el-collapse-item>
      <el-collapse-item
        v-if="activatedNode.compData.dataSourceType
          && activatedNode.compData.dataSourceType !== '输入参数'"
        title="数据映射"
        name="mapping"
      >
        <div class="data-list">
          <div
            class="data-item"
            v-for="(field, index) in activatedNode.compData.fieldList || []"
            :key="index"
          >
            <div class="label">
              <span v-if="field.builtin">{{field.name}}：</span>
              <el-input
                v-else
                v-model="field.name"
                style="padding-right: 5px"
                placeholder="字段名"
                size="small"
              />
            </div>
            <ac-select
              v-model="field.value"
              :options="fieldNameList"
              allowCreate
              size="small"
            />
            <ac-select
              v-if="activatedNode.compData.dataSourceType === '脚本'"
              v-model="field.type"
              :options="[
                {key: '日期', value: '日期'},
                {key: '时间', value: '时间'}
              ]"
              style="width: 170px;padding-left: 5px;"
              size="small"
              title="数据类型"
            />
            <ac-icon
              iconId="018dc9c3efd3a0502886"
              title="删除"
              color="red"
              size="small"
              @click="deleteDataField(index)"
            />
          </div>
        </div>
        <div class="data-add-box">
          <div class="data-add">
            <ac-icon iconId="018dca3b4707c4c43a2f" />
            <span style="font-size: 13px;" @click="addDataField">添加映射</span>
            <ac-icon style="margin-left: 15px" iconId="018ece4f72d1bf69178b" />
            <span style="font-size: 13px" @click="addAllDataField">一键添加</span>
          </div>
        </div>
      </el-collapse-item>
      <el-collapse-item
        v-if="activatedNode.compData.dataSourceType"
        title="数据响应结果"
        name="dataList"
      >
        <template #title>
          <span style="margin-right: 10px">数据响应结果</span>
          <ac-icon
            iconId="018dc9c3efd289739df0"
            @click.stop="activatedNode.compData.refresh = !activatedNode.compData.refresh"
          />
        </template>
        <div class="data-list">
          <div class="data-item">
            <div class="content">
              <ac-textarea
                v-model="activatedNode.compData.dataList"
                :rows="10"
                size="small"
              />
            </div>
          </div>
        </div>
      </el-collapse-item>
    </el-collapse>
  </div>
  <div v-else class="not-support">此组件不支持数据</div>

  <!--新增编辑界面-->
  <el-dialog
    :title="dialogTitle"
    v-model="dialogVisible"
    :close-on-click-modal="false"
    destroy-on-close
    fullscreen
    append-to-body
  >
    <div class="page-container">
      <div v-if="dialogEdit" style="margin-bottom: 5px">
        <el-button
          size="default"
          type="success"
          @click="addDialogData"
        >添加1行</el-button>
        <el-button
          size="default"
          type="success"
          @click="addDialogColumn"
        >添加1列</el-button>
      </div>
      <el-table
        :show-overflow-tooltip="true"
        :class="['data-table', dialogEdit ? 'edit-table' : '']"
        width="100%"
        :data="dialogDataList"
        :border="true"
        :stripe="true"
      >
        <template #empty>
          <div class="el-table__empty-block">
            <img src="@/assets/images/no-data.png" style="width: 100px" alt />
            <span style="min-width: 100px">暂无数据</span>
          </div>
        </template>
        <el-table-column
          v-for="column in dialogColumns"
          header-align="center"
          align="center"
          :label="column.prop"
          :min-width="120"
          :key="column.prop"
          :show-overflow-tooltip="dialogEdit ? false : {
            'effect': 'light',
            'raw-content': false,
            'placement': 'bottom',
            'popper-class': 'padding-10-15'
          }"
        >
          <template #header>
            <div
              v-if="dialogEdit"
              style="width: 100%;display: flex;flex-direction: row"
            >
              <el-input v-model="dialogMapping[column.prop]" />
              <el-button
                type="danger"
                @click="delDialogColumn(column)"
                link
              >删除</el-button>
            </div>
            <div v-else>{{dialogMapping[column.prop]}}</div>
          </template>
          <template v-slot="scope">
            <div v-if="dialogEdit" style="width: 100%;">
              <el-input
                v-model="scope.row[column.prop]"
              />
            </div>
            <div v-else>{{scope.row[column.prop]}}</div>
          </template>
        </el-table-column>
        <el-table-column
          header-align="center"
          align="center"
          label="操作"
          width="50"
        >
          <template #default="scope">
            <el-button
              type="danger"
              @click="delDialogData(scope.row)"
              link
            >删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <template #footer>
      <el-button
        v-if="dialogEdit"
        size="default"
        type="info"
        @click="dialogVisible = false"
      >取消</el-button>
      <el-button
        v-if="dialogEdit"
        size="default"
        type="primary"
        @click="submitDialog"
      >确定</el-button>
      <el-button
        v-if="!dialogEdit"
        size="default"
        type="info"
        @click="dialogVisible = false"
      >关闭</el-button>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, watch, onMounted, inject, nextTick, computed } from 'vue';
import tool from "@/utils/tool";
import api from "@/http/api";
import { ElMessageBox } from "element-plus";

const rootNode = inject('rootNode');
const activatedNode = inject('activatedNode');
const collapseNames = ref(['param', 'dataSource', 'dataFilter', 'dataOrdinal', 'dataQuery', 'mapping', 'dataList'])
const dialogTitle = ref('');
const dialogVisible = ref(false);
const dialogEdit = ref(false);
const dialogMapping = ref({});
const dialogColumns = ref([]);
const dialogDataList = ref([]);
const fieldIdList = ref();
const fieldNameList = ref();
const nodeOptions = ref();
const pageParamList = inject("pageParamList");

const addInputParam = () => {
  if (!activatedNode.value.compData.inputParamList) {
    activatedNode.value.compData.inputParamList = [];
  }
  activatedNode.value.compData.inputParamList.push({id: tool.uuids(), name: ''});
  initNodeOptions();
};

const deleteInputParam = (index) => {
  ElMessageBox.confirm("请确认是否删除？", "提示", { type: "warning" }).then(() => {
    activatedNode.value.compData.inputParamList.splice(index, 1);
    initNodeOptions();
  }).catch(() => {});
};

const globalParamOptions = computed(() => {
  const options = [];
  (pageParamList.value || []).forEach(param => {
    options.push({key: param.id || '', value: '[全局参数].' + (param.name || '参数名')});
  });

  const nodes = tool.getParentNodes(rootNode.value, activatedNode.value.id);
  for (const node of nodes) {
    const dataNode = tool.findNodeById(rootNode.value, node.id);
    if (dataNode?.compData?.fieldList?.length > 0) {
      options.push({key: 'list.' + node.id + '.row', value: node.name + '.行.值'});
    }
    (dataNode?.compData?.fieldList || []).forEach(field => {
      options.push({key: 'list.' + node.id + '.row.' + field.name, value: node.name + '.行.' + field.name + '.值'});
    });
  }
  return options;
});

const inputParamOptions = computed(() => {
  const options = [];
  (activatedNode.value.compData?.inputParamList || []).forEach(param => {
    options.push({key: param.id || '', value: '[组件入参].' + (param.name || '参数名')});
  });
  return options;
});

const addDataField = () => {
  if (!activatedNode.value.compData.fieldList) {
    activatedNode.value.compData.fieldList = [];
  }
  activatedNode.value.compData.fieldList.push({id: tool.uuids(), name: '', value: ''});
};

const addAllDataField = () => {
  if (!activatedNode.value.compData.fieldList) {
    activatedNode.value.compData.fieldList = [];
  }

  if (Array.isArray(fieldNameList.value)) {
    fieldNameList.value.forEach(item => {
      activatedNode.value.compData.fieldList.push({id: tool.uuids(), name: item.value, value: item.key});
    });
  } else {
    (fieldNameList.value || '').split(',').forEach(item => {
      activatedNode.value.compData.fieldList.push({id: tool.uuids(), name: item, value: item});
    });
  }
};

const deleteDataField = (index) => {
  activatedNode.value.compData.fieldList.splice(index, 1);
};

const addFilter = () => {
  if (!activatedNode.value.compData.filterList) {
    activatedNode.value.compData.filterList = [];
  }
  activatedNode.value.compData.filterList.push({name: '', value: ''});
};

const addAllFilter = () => {
  if (!activatedNode.value.compData.filterList) {
    activatedNode.value.compData.filterList = [];
  }

  (nodeOptions.value || []).forEach(option => {
    activatedNode.value.compData.filterList.push({
      manually: false,
      fieldId: option.value && option.value.indexOf('.') ? option.value.split('.')[0] : option.value,
      compareValue: option.key
    });
  });
};

const moveFilterUp = (index) => {
  const curr = activatedNode.value.compData.filterList[index];
  activatedNode.value.compData.filterList[index] = activatedNode.value.compData.filterList[index - 1];
  activatedNode.value.compData.filterList[index - 1] = curr;
};

const moveFilterDown = (index) => {
  const curr = activatedNode.value.compData.filterList[index];
  activatedNode.value.compData.filterList[index] = activatedNode.value.compData.filterList[index + 1];
  activatedNode.value.compData.filterList[index + 1] = curr;
};

const deleteFilter = (index) => {
  ElMessageBox.confirm("请确认是否删除？", "提示", { type: "warning" }).then(() => {
    activatedNode.value.compData.filterList.splice(index, 1);
  }).catch(() => {});
};

const addOrdinal = () => {
  if (!activatedNode.value.compData.ordinalList) {
    activatedNode.value.compData.ordinalList = [];
  }
  activatedNode.value.compData.ordinalList.push({name: '', value: ''});
};

const moveOrdinalUp = (index) => {
  const curr = activatedNode.value.compData.ordinalList[index];
  activatedNode.value.compData.ordinalList[index] = activatedNode.value.compData.ordinalList[index - 1];
  activatedNode.value.compData.ordinalList[index - 1] = curr;
};

const moveOrdinalDown = (index) => {
  const curr = activatedNode.value.compData.ordinalList[index];
  activatedNode.value.compData.ordinalList[index] = activatedNode.value.compData.ordinalList[index + 1];
  activatedNode.value.compData.ordinalList[index + 1] = curr;
};

const deleteOrdinal = (index) => {
  ElMessageBox.confirm("请确认是否删除？", "提示", { type: "warning" }).then(() => {
    activatedNode.value.compData.ordinalList.splice(index, 1);
  }).catch(() => {});
};

const changeDataSourceType = () => {
  if (activatedNode.value.compData.dataSourceType === '静态数据') {
    changeDataJson();
  } else if (activatedNode.value.compData.dataSourceType === '数据模型') {
    changeDataModel();
  }
};

const changeDataJson = () => {
  fieldIdList.value = [];
  fieldNameList.value = [];
  if (!activatedNode.value.compData.dataJson) return;

  try {
    const fieldNames = [];
    const json = JSON.parse(activatedNode.value.compData.dataJson);
    for (let p in (json && json[0]) || {}) {
      if (fieldNames.indexOf(p) < 0) {
        fieldNames.push(p);
      }
    }
    fieldIdList.value = fieldNames.join(',');
    fieldNameList.value = fieldNames.join(',');
  } catch (e) {
    console.log("解释静态数据出错！", e)
  }
};

const changeDataModel = () => {
  fieldIdList.value = [];
  fieldNameList.value = [];
  if (!activatedNode.value.compData.dataModelId) return;

  const data = {modelId: activatedNode.value.compData.dataModelId};
  api.post('/system/dataField/queryList', data).then(res => {
    fieldIdList.value = (res.data || []).map(item => ({key: item.id, value: item.showName}));
    fieldNameList.value = (res.data || []).map(item => ({key: item.fieldName, value: item.showName}));
  });
};

const changeView = () => {
  fieldIdList.value = [];
  fieldNameList.value = [];
  if (!activatedNode.value.compData.viewId) return;

  const data = {id: activatedNode.value.compData.viewId};
  api.post('/system/view/queryColumn', {id: data}).then(res => {
    fieldIdList.value = (res.data && res.data.columnList || []).map(item => item.columnName).join(',');
    fieldNameList.value = (res.data && res.data.columnList || []).map(item => item.columnName).join(',');
  });
};

const changeScript = () => {
  fieldIdList.value = [];
  fieldNameList.value = [];
  if (!activatedNode.value.compData.scriptId) return;

  const data = {};
  api.runScript(activatedNode.value.compData.scriptId, data).then(res => {
    const fieldNames = [];
    Object.keys((res && res.data && res.data[0]) || {}).forEach(key => {
      if (fieldNames.indexOf(key) < 0) {
        fieldNames.push(key);
      }
    });
    fieldIdList.value = fieldNames.join(',');
    fieldNameList.value = fieldNames.join(',');
  });
};

const initNodeOptions = () => {
  let options = [];
  tool.walkTree(rootNode.value, (node) => {
    if (!node.type || node.type === 'form-item' || !node.type.startsWith('form-')) return;
    options.push({key: node.id + '.value', value: node.name + '.值'});
  });

  options = options.sort((a, b) => a.value.localeCompare(b.value));

  const inputParamList = [];
  (activatedNode.value.compData.inputParamList || []).forEach(inputParam => {
    inputParamList.push({
      key: 'inputParam.' + inputParam.id,
      value: '[组件入参].' + inputParam.name}
    );
  });
  options.unshift(...inputParamList);
  nodeOptions.value = options;
};

const init = async() => {
  if (!activatedNode.value.compData.dataSourceType
      || activatedNode.value.compData.dataSourceType === '静态数据') {
    changeDataJson();
  } else if (activatedNode.value.compData.dataSourceType === '数据模型') {
    changeDataModel();
  } else if (activatedNode.value.compData.dataSourceType === '视图') {
    changeView();
  } else if (activatedNode.value.compData.dataSourceType === '脚本') {
    changeScript();
  }
  initNodeOptions();

  if (!fieldNameList.value) {
    fieldNameList.value = 'clear.options';
  }
};

const editDataList = (json) => {
  const dataList = json ? (JSON.parse(json) || []) : [];
  const columnList = [];
  const dataMap = {};
  const resultList = [];
  dataList.forEach(data => {
    const result = {rowFlag: tool.uuid()};
    for (const p in data) {
      let id = null;
      for (const key in dataMap) {
        if (dataMap[key] === p) {
          id = key;
          break;
        }
      }

      if (!id) {
        id = tool.uuid();
        dataMap[id] = p;
        columnList.push({prop: id});
      }
      result[id] = data[p];
    }
    resultList.push(result);
  });

  if (Object.keys(dataMap).length === 0
      && activatedNode.value.compData?.fieldList?.length > 0) {
    activatedNode.value.compData?.fieldList.forEach(field => {
      const id = tool.uuid();
      dataMap[id] = field.name;
      columnList.push({prop: id});
    });
  }
  dialogMapping.value = dataMap;
  dialogColumns.value = columnList;
  dialogDataList.value = resultList;
  dialogVisible.value = true;
  dialogEdit.value = true;
  dialogTitle.value = "数据编辑";
};

const addDialogColumn = () => {
  dialogColumns.value.push({prop: tool.uuid()});
};

const delDialogColumn = (column) => {
  const index = dialogColumns.value.findIndex(item => item.prop === column.prop);
  dialogColumns.value.splice(index, 1);
};

const addDialogData = () => {
  dialogDataList.value.push({rowFlag: tool.uuid()});
};

const delDialogData = (row) => {
  const index = dialogDataList.value.findIndex(item => item.rowFlag === row.rowFlag);
  dialogDataList.value.splice(index, 1);
};

const submitDialog = () => {
  const resultList = [];
  dialogDataList.value.forEach(data => {
    const result = {};
    for (const key in dialogMapping.value) {
      result[dialogMapping.value[key]] = data[key];
    }
    resultList.push(result);
  });
  activatedNode.value.compData.dataJson = JSON.stringify(resultList);
  dialogVisible.value = false;
  changeDataJson();
};

watch(() => activatedNode.value.id, async() => {
  await nextTick(() => init());
});

watch(() => activatedNode.value.compData, () => {
  rootNode.value.unSave = true;
}, {deep: true});

onMounted(() => {
  init();
});
</script>

<style scoped lang="scss">
.not-support {
  color: #dcdcdc;
  padding: 8px;
  text-align: center;
  width: 100%;
}
.data-box {
  display: flex;
  flex-direction: column;
  .data-list {
    margin: 5px;
    display: flex;
    flex-direction: column;
    .data-item {
      display: flex;
      flex-direction: row;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 5px;
      color: #dcdcdc;
      border-radius: 5px;
      font-size: 14px !important;

      .label {
        width: 100px;
        padding-left: 5px;
        text-align: right;
        white-space: nowrap;
        font-size: 13px;
        overflow: hidden;
        text-overflow: ellipsis;
        flex-shrink: 0;
        :deep(.el-tooltip__trigger) {
          display: flex;
          flex-direction: row;
          justify-content: end;
          align-items: center;
        }
      }

      .content {
        width: 1px;
        flex-grow: 1;
        display: flex;
        flex-direction: row;
      }

      .ac-icon {
        flex-shrink: 0;
        margin-left: 5px;
        cursor: pointer;
      }
    }
    .data-item:last-child {
      margin-bottom: 0;
    }
  }
  .filter {
    .data-list {
      &:nth-last-child(2) {
        padding-bottom: 0;
        border-bottom: none!important;
      }
    }
  }
}
.data-add-box {
  display: flex;
  flex-direction: row;
  justify-content: center;
  align-items: center;
  padding: 5px 8px;
  color: #dcdcdc;
  height: 30px;
  .data-add {
    display: flex;
    flex-direction: row;
    justify-content: center;
    align-items: center;
    cursor: pointer;
  }
}
:deep(.el-radio-button) {
  --el-radio-button-checked-bg-color: #555;
  --el-radio-button-checked-text-color: #dcdcdc;
  --el-radio-button-checked-border-color: #333;
  --el-radio-button-disabled-checked-fill: #333;
}
:deep(.el-radio-button) .el-radio-button__inner {
  color: #dcdcdc;
  background: #555555;
  border-right: 1px solid #333;
  border-top: 1px solid #333;
  border-bottom: 1px solid #333;
  padding: 5px 6px;
}
:deep(.el-radio-button:first-child) .el-radio-button__inner {
  border-left: 1px solid #333;
}
:deep(.el-radio-button).is-active .el-radio-button__inner {
  background: #333!important;
}
</style>